﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Lswweb.Common;
using Lswweb.Domain;
using Lswweb.Model;

namespace Lswweb.Controls
{
    public abstract class SkinnedEditControl<TModel> : SkinnedWebControl
    {
        private IButtonControl btnConfirm;

        protected override void InitializeSkin(Control skin)
        {
            this.InitSkin(skin);
            btnConfirm = (IButtonControl)skin.FindControl(this.BtnControlId);

            if (btnConfirm != null)
            {
                btnConfirm.Click += new EventHandler(btnConfirm_Click);
            }

            skin.Load += new EventHandler(skin_Load);
        }

        void skin_Load(object sender, EventArgs e)
        {
            TModel model = this.FindById(this.Id);
            if (model != null && !Page.IsPostBack)
            {
                this.ModelByFrom = model;
            }
        }

        void btnConfirm_Click(object sender, EventArgs e)
        {
            TModel model = this.ModelByFrom;

            try
            {
                model.SetPropertyValue("Id", this.Id);
            }
            catch (ArgumentOutOfRangeException) { }

            if (Id > 0)
            {
                this.Update(model);
            }
            else
            {
                this.Add(model);
            }
        }

        protected virtual string BtnControlId
        {
            get { return "btnConfirm"; }
        }

        private int id = SiteContext.Current.Id;
        protected virtual int Id
        {
            get { return id; }
        }

        protected abstract TModel ModelByFrom { get; set; }

        protected abstract void Add(TModel model);

        protected abstract void Update(TModel model);

        protected abstract TModel FindById(int id);

        protected abstract void InitSkin(Control skin);
    }
}
